package com.zcj.demo.web.user.rest;

import com.zcj.demo.user.service.AccountService;
import com.zcj.demo.user.service.dto.UserDTO;
import com.zcj.demo.web.user.vo.LoginVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @author 68300119
 * @Date 2020/10/13
 **/
@RestController
@RequestMapping("/api")
public class AccountController {

    private final AccountService accountService;

    public AccountController(AccountService accountService) {
        this.accountService = accountService;
    }

    @GetMapping("/login/captcha")
    public ResponseEntity<Void> getCaptcha(String mobile) {
        accountService.sendCaptcha(mobile);
        return ResponseEntity.ok().build();
    }

    /**
     * 登录
     *
     * @param params 登录信息
     * @return
     */
    @PostMapping(value = "/login/account")
    public ResponseEntity<String> login(@RequestBody LoginVO params) {
        accountService.login(params);
        return ResponseEntity.ok("ok");
    }

    /**
     * 退出
     */
    @GetMapping("/logout")
    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
    }

    /**
     * 当前用户
     *
     * @return 用户信息
     */
    @GetMapping("/currentUser")
    public ResponseEntity<UserDTO> currentUser() {
        UserDTO user = (UserDTO) SecurityUtils.getSubject().getPrincipal();
        user.setPassword(null);
        return ResponseEntity.ok(user);
    }

    /**
     * 注册
     *
     * @param user 用户信息
     * @return 用户信息
     */
    @PostMapping("/register")
    public ResponseEntity<UserDTO> register(@RequestBody UserDTO user) {
        user.setUsername(user.getEmail());
        UserDTO result = accountService.register(user);
        result.setPassword(null);
        return ResponseEntity.ok(result);
    }
}
